<?php

namespace App\Http\Controllers\Common;

use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Models\Common\Area;
use Illuminate\Http\File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use phpDocumentor\Reflection\Types\Null_;

/**
 * @group 区域地址
 * Class AreaController
 * @package App\Http\Controllers\Common
 */
class AreaController extends Controller
{

    /**
     * getAreaJson json 地址数据
     * @time:2020/2/9-12:43
     * @author:dongdong
     * @queryParam example_id required The id of the location.
     * @bodyParam example_id required The id of the location.
     * @response {
     * "data": {
     * },
     * "status_code": 200,
     * "message" : "success"
     * }
     */
    public function getAreaJson()
    {
        $json = Storage::disk('public')->get('area.json');
        $data = json_decode($json,true);

        return returnData($data);
    }

    /**
     * getChildArea 获取下级区域地址 default 第一级数据
     * @time:2020/2/9-13:07
     * @author:dongdong
     * @response {
     * "data": {
     * },
     * "status_code": 200,
     * "message" : "success"
     * }
     */
    public function getChildArea(Request $request)
    {
        $pcode = $request->get('pcode',Null);
        if ($pcode) {
            $area = Area::query()->where('pcode',$pcode)->get();
        }
        else {
            $area = Area::query()->whereNull('pcode', $pcode)->get();
        }
        return returnData($area);
    }

    /**
     * queryName 查询区域名称
     * @time:2020/2/10-10:44
     * @author:dongdong
     * @queryParam code required 区域code. Example:110101
     * @response {
     * "data": {
     * },
     * "status_code": 200,
     * "message" : "success"
     * }
     */
    public function queryName(Request $request)
    {
        $code = $request->get('code');
        $request->validate([
            'code' => 'required|exists:areas'
        ]);

        $data = Area::query()->where('code', $code)->first();
        if ($data) {
            return returnData($data);
        }

        throw new ApiException('数据不存在');
    }


    /**
     * getChildFormat 【laravel-admin 数据格式】获取下级区域地址 default 第一级数据
     * @time:2020/2/9-13:07
     * @author:dongdong
     * @queryParam  q 查询参数 为地址编码 Example:130000
     * @response {
     * "data": {
           {
              "code":"100012",
             "text":"名称"
          }
      },
     * "status_code": 200,
     * "message" : "success"
     * }
     */
    public function getChildFormat(Request $request)
    {
        $pcode = $request->get('q',Null);
        if ($pcode) {
            $area = Area::query()->where('pcode',$pcode)->get(["code as id",'text']);
        }
        else {
            $area = Area::query()->whereNull('pcode', $pcode)->get(["code as id",'text']);
        }
        return response($area);
    }

}
